import axios from "axios"
import Cookies from "js-cookie"
import pinia from "../store"
import { userStore } from "../store/user";
import { post, get } from './axios'
import { URL } from "./URL";
import router from "../router";
const user = userStore(pinia)

//axios中断请求
var { CancelToken } = axios;
var source = CancelToken.source()

/* 
    func:sendImage
    AI绘画接口
    上传描述信息，返回图片url
*/
const sendImage = (message) => {
    return new Promise((resolve, reject) => {
        let data = {
            question: message,
            count: "1",
            size: "512x512"
        }
        let config = {
            cancelToken: source.token
        }
        post(URL.BASE_GETCHATGPTIMAGE_URL, data, config).then(res => {
            // console.log(res);
            resolve(res.data.data[0].url)
        }).catch(error => {
            reject()
        })
    })
}




/*
    func:checkLogin
    判断是否登录，token是否过期
    未登录or过期：返回0
    成功登录:返回level
*/
const checkLogin = () => {
    return get(URL.BASE_CHECK_SESSION)
}





/*
    func:checkLevel
    判断是否是管理员
    是：返回1
    否：返回0
*/
const checkLevel = () => {
    return new Promise((resolve, reject) => {
        get(URL.BASE_CHECKLOGIN_URL).then(res => {
            resolve(res.data.data)
        }).catch(err => {
            reject(err)
        })
    })
}






/*
    func:Login()
    登录接口
    成功登录：返回1，并存储Token
    密码错误：返回2
    无此用户：返回0
*/
const Login = (username, password) => {
    let data = {
        username: username,
        password: password
    }
    // 返回Promise
    return new Promise((resolve, reject) => {
        console.log('data:', data);
        post(URL.BASE_LOGIN_URL, data)
            .then(res => {
                // console.log(res.data.code);
                // 判断是否登陆成功 200成功 100成功 400密码错误
                if (res.data.code == 400) {
                    resolve(0)
                } else if (res.data.code == 400) {
                    resolve(2)
                } else if (res.data.code == 200) {
                    // 将获取的Token存入cookie中 持续14天
                    // Cookies.set('Token', res.data.data.token, { expires: 14 })
                    resolve(1)
                }
            })
            .catch(error => {
                reject(error)
            })
    })
}



// 添加白名单接口
const addAccount = (username, password) => {
    return new Promise((resolve, reject) => {
        let data = {
            username: username,
            password: password
        }
        post(URL.BASE_REGISTER_URL, data).then(res => {
            console.log(res);
            if (res.data.code == 200) {
                resolve(1)
            } else {
                resolve(0)
            }
        }).catch(err => {
            reject(err)
        })
    })
}



// 退出登录
const LogOut = () => {
    return new Promise((resolve) => {
        get(URL.BASE_LOGOUT_URL).then(res => {
            console.log(res);
            resolve()
        })
        user.resetAll()
    })
}


// 用户退出页面
const deleteStorage = () => {
    get(URL.BASE_CLEAN_URL).then(res => {
        console.log(res);
    })
}


// 获取tokens
const getTokens = () => {
    console.log("getTokesn");
    return new Promise((resolve, reject) => {
        get(URL.BASE_GETTOKEN_URL).then(res => {
            // console.log(res);
            let { count, last_count, count_gpt4, last_count_gpt4 } = res.data.data
            updateTokens(count, last_count, count_gpt4, last_count_gpt4)
            resolve(res.data.count)
        }).catch(err => {
            reject(err)
        })
    })
}

/* 
    获取用户列表
    请求方式:GET
    params:pagenum,pageSize 
*/
const getUsers = (pageNum, pageSize) => {
    return new Promise((resolve, reject) => {
        get(URL.BASE_GETUSERS_URL, {
            params: {
                pageNum: pageNum,
                pageSize: pageSize
            }
        }).then(res => {
            // console.log(res);
            resolve(res.data.data)
        })
    })
}

/* 
    修改密码
    返回1：成功
    返回2：密码错误
*/
const changePassword = (oldPassword, newPassword) => {
    return new Promise((resolve, reject) => {
        let data = {
            password: oldPassword,
            newpassword: newPassword
        }
        post(URL.BASE_CHANGEPASSWORD_URL, data).then(res => {
            if (res.data.code == 200) {
                resolve(1)
            }
            else if (res.data.code == 400) {
                resolve(2)
            }
            else {
                resolve(0)
            }
        }).catch(err => {
            reject(err)
        })
    })
}

/*
    中断AI的回应
*/
const Cancel = () => {
    source.cancel("手动取消")
    source = CancelToken.source()
}


/* 
    更新tokens到pinia
*/
const updateTokens = (total_tokens, old_tokens, total_tokens_GPT4, old_tokens_GPT4) => {
    user.updateTokens(total_tokens)
    user.setOldTokens(old_tokens)
    user.total_tokens_GPT4 = total_tokens_GPT4
    user.old_tokens_GPT4 = old_tokens_GPT4
}

/*
    提交bug
*/
const sendBug = (bug) => {
    return new Promise((resolve, reject) => {
        get("/email/sendemail", {
            params: {
                content: bug
            }
        }).then(res => {
            resolve(res.data.code)
            console.log(res);
        }).catch(err => {
            reject(err)
        })
    })
}
export { URL, Login, addAccount, checkLogin, LogOut, deleteStorage, getTokens, getUsers, sendImage, changePassword, Cancel, checkLevel, sendBug }